// 计算两点间距离（米）Haversine公式。
export function calculateDistance(lat1, lng1, lat2, lng2) {
	const radLat1 = lat1 * Math.PI / 180.0;
	const radLat2 = lat2 * Math.PI / 180.0;
	const a = radLat1 - radLat2;
	const b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
	let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
		Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
	s = s * 6378.137; // EARTH_RADIUS
	s = Math.round(s * 10000) / 10;
	return s;
}
//计算两点间距离（米）Vincenty公式 ,暂无法使用
export function vincentyDistance(lat1, lon1, lat2, lon2) {
	const a = 6378137; // WGS84赤道半径 (m)
	const f = 1 / 298.257223563; // 扁率
	const b = (1 - f) * a; // 极半径

	const L = (lon2 - lon1) * Math.PI / 180;
	const U1 = Math.atan((1 - f) * Math.tan(lat1 * Math.PI / 180));
	const U2 = Math.atan((1 - f) * Math.tan(lat2 * Math.PI / 180));
	const sinU1 = Math.sin(U1),
		cosU1 = Math.cos(U1);
	const sinU2 = Math.sin(U2),
		cosU2 = Math.cos(U2);

	let λ = L,
		λPrev, iterLimit = 100;
	let cosSqα, sinσ, cosσ, σ, cos2σM;

	do {
		const sinλ = Math.sin(λ),
			cosλ = Math.cos(λ);
		sinσ = Math.sqrt((cosU2 * sinλ) ** 2 + (cosU1 * sinU2 - sinU1 * cosU2 * cosλ) ** 2);
		if (sinσ === 0) return 0; // 重合点
		cosσ = sinU1 * sinU2 + cosU1 * cosU2 * cosλ;
		σ = Math.atan2(sinσ, cosσ);
		const sinα = cosU1 * cosU2 * sinλ / sinσ;
		cosSqα = 1 - sinα ** 2;
		cos2σM = cosσ - 2 * sinU1 * sinU2 / cosSqα;
		λPrev = λ;
		λ = L + (1 - f) * a * sinα / (cosU1 * cosU2 * sinσ) * (σ + cos2σM);
	} while (Math.abs(λ - λPrev) > 1e-12 && --iterLimit > 0);

	if (iterLimit === 0) throw new Error("Vincenty公式未收敛");

	const C = f / 16 * cosSqα * (4 + f * (4 - 3 * cosSqα));
	const λDiff = λ - λPrev;
	const s = b * a * (σ - C * sinσ * (cos2σM + C * cosσ * (-1 + 2 * cos2σM ** 2)));

	return Math.sqrt(s) / 1000; // 转换为公里，保留小数点后3位
}